import Mock from 'mockjs'

// get请求从config.url获取参数，post从config.body中获取参数
function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"') +
    '"}'
  )
}

let List = []
const count = 200

for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id:Mock.Random.integer(0, 49999),
      model: Mock.Random.integer(1, 5),
      data: Mock.Random.date(),
      count: Mock.Random.integer(5000, 100000),
      stock: Mock.Random.integer(0, 49999),
      price:Mock.Random.integer(1500, 10000),
    })
  )
}

export default {
  /**
   * 获取列表
   * 要带参数 id, page, limt; name可以不填, page,limit有默认值。
   * @param id, page, limit
   * @return {{code: number, count: number, data: *[]}}
   */
  getPhoneList: config => {
    const { id, page = 1, limit = 20 } = param2Obj(config.url)
    console.log('id:' + id, 'page:' + page, '分页大小limit:' + limit)
    const mockList = List.filter(phoneInfo => {
      if (id && phoneInfo.id===id) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    return {
      code: 20000,
      count: mockList.length,
      list: pageList
    }
  },
  /**
   * 增加用户
   * @param id, model, data, count, stock,price
   * @return {{code: number, data: {message: string}}}
   */
  createPhone: config => {
    const {  model, data, count,price } = JSON.parse(config.body)
    console.log(JSON.parse(config.body))
    List.unshift({
      id:Mock.Random.integer(0, 49999),
      model: model,
      data: data,
      count: count,
      stock: Mock.Random.integer(0, 9999),
      price: price
    })
    return {
      code: 20000,
      data: {
        message: '添加成功'
      }
    }
  },
  /**
   * 删除用户
   * @param id
   * @return {*}
   */
  deletePhone: config => {
    const { id } = param2Obj(config.url)
    if (!id) {
      return {
        code: -999,
        message: '参数不正确'
      }
    } else {
      List = List.filter(u => u.id !== id)
      return {
        code: 20000,
        message: '删除成功'
      }
    }
  },
  /**
   * 修改用户
   * @param model, addr, age, birth, sex
   * @return {{code: number, data: {message: string}}}
   */
  updatePhone: config => {
    const { id, model, data, count, stock,price } = JSON.parse(config.body)
    List.some(u => {
      if (u.id === id) {
        u.model = model
        u.data = data
        u.count = count
        u.stock = stock
        u.price = price
        return true
      }
    })
    return {
      code: 20000,
      data: {
        message: '编辑成功'
      }
    }
  }
}
